-- SPDX-License-Identifier: GPL-3.0-or-later
---@class StoryData: Object
local Shop = class("Shop")
local WU = require "packages/wdtx/WUltiity"
function Shop:initialize(player,data,obj)
  self.player = player
  self.room = player.room
  self.shopdata = data
  self.wdtxobj = obj
  self.curskills = {}
  self.curcards = {}
  self.forgetgold = 5
  self.upgold = 6
  self:initShopSkills()
end

function Shop:initShopSkills()
  local shopdata = self:getShopData()
  self.shopskills = table.clone(shopdata.buyskills)
end

function Shop:getShopData()
  return self.shopdata[self.wdtxobj.storyid]
end

function Shop:removeSameSkills(skills)
  WU:removeSameItemsByTB(skills,self.shopskills,"name")
end

function Shop:buySkills()   --购买技能
  if #self.curskills == 0 then 
    self.curskills = table.random(self.shopskills,math.min(#self.shopskills,6))
  end
  local reply = self.room:askForCustomDialog(self.player,"buyskills","packages/wdtx/qml/ShopBuySkill.qml",{"buyskills",self.curskills,1,1,self.player:getMark("@gold_num")})
  if reply == "" then return end
  reply = json.decode(reply)
  if reply and reply ~= "" and #reply > 0 then
    local buyski = table.remove(self.curskills,reply[1])
    local chs = buyski.name
    if not self.player:hasSkill(chs) then
      self.room:removePlayerMark(self.player,"@gold_num",buyski.cost)
      self.room:handleAddLoseSkills(self.player, chs, nil, false)
      self.room:doBroadcastNotify("ShowToast", Fk:translate(self.player.general) .."购买"..Fk:translate(chs))
      self.wdtxobj:removeSameSkills({chs})
    else
      self.room:doBroadcastNotify("ShowToast", Fk:translate(self.player.general) .."已经有了"..Fk:translate(chs))
    end    
    if #self.curskills == 0 then 
      table.removeOne(self.shop_chc,"buyskills")
      self.room:doBroadcastNotify("ShowToast", "技能全部售卖完。请下次再来") 
      return 
    end
    return self:buySkills()
  end
  return 
end

function Shop:getShopItems(num)   --商店卡牌
  local cardsdata = self:getShopData().buycards
  local weight_data = WU:getItemsByWeight(num,cardsdata.weight)
  --检索随机到卡牌类型随机的卡牌
  local data = {}
  local cardtypes = {}
  for _,t in ipairs(weight_data) do
    local name = WU:getItemByRate(cardsdata[t],data)
    if not data[name] then
      data[name] = 1
      cardtypes[name] = t
    else
      data[name] = data[name] + 1
    end
  end

  local cards = self.wdtxobj:findCards(data,self.room.void)
  local shopcards = {}
  for _,cid in ipairs(cards) do
    local card = Fk:getCardById(cid)
    local tp = cardtypes[card.name]
    local cfg = cardsdata[tp][card.name]
    local rate_idx = WU:getItemByWeight(cfg.uprate)
    local price = cfg.price[rate_idx]
    -- p(cfg.uprate)
    -- p(rate_idx)
    -- p(price)
    -- dbg()
    if price then
      local setlv = rate_idx - 1
      if setlv > 0 then
        self.wdtxobj:setCardMark(card,setlv)
      end  
      table.insert(shopcards,{cid=cid,price=price})
    else
      error(string.format("该卡牌配置数据有错误", card.name))
    end  
  end
  return shopcards
end

function Shop:buyCards()   --购买卡牌
  local shopcards
  if #self.curcards == 0 then
    shopcards = self:getShopItems(8)
  else
    shopcards = self.curcards
  end
  
  -- if #shopcards > 0 then
  --   for _, da in ipairs(shopcards) do
  --     local card = Fk:getCardById(da.cid)
  --     p(card.name)
  --     p(card.mark)
  --   end
  -- end
  -- p(shopcards)
  -- dbg()
  local cardstr = "来买一些吧，童叟无欺，价格公道。<font color='red'><b>（只有钱够，卡牌任意多选）</b></font>"
  local reply = self.room:askForCustomDialog(self.player,"buycards","packages/wdtx/qml/ShopCardsBox.qml",{"buycards",cardstr,shopcards,{"OK","Exist"},self.player:getMark("@gold_num")})
  if reply ~= "" then
    reply = json.decode(reply)
    if reply.cards and #reply.cards > 0 then --刷新商店卡牌
      -- local cards = {}
      local cur,rem_num = 0,0
      while rem_num < #reply.cards do
        cur = cur + 1
        local cid = shopcards[cur].cid
        for _, da in ipairs(reply.cards) do
          if da.cid == cid then
            table.remove(shopcards,cur)
            cur = 0
            rem_num = rem_num + 1
            break
          end
        end
      end
      self.curcards = shopcards

      local getcards = {}
      local totcost,buystr = 0,""
      for _, da in ipairs(reply.cards) do
        local card = Fk:getCardById(da.cid)
        table.insert(getcards,da.cid)
        totcost = totcost + da.price
        buystr = buystr + Fk:translate(card.name) + "，"
      end
      self.room:removePlayerMark(self.player,"@gold_num",totcost)
      self.room:doBroadcastNotify("ShowToast", Fk:translate(self.player.general) .."购买："..buystr)
      self.wdtxobj:inputPipleByGet(getcards,"self_draws")
    else
      self.curcards = shopcards
    end
    if #self.curcards == 0 then
      table.removeOne(self.shop_chc,"buycards")
    end
  end
end

function Shop:forgetCards(num,peradd)   --遗忘卡牌
  local playergold = self.player:getMark("@gold_num") 
  -- if playergold < self.forgetgold then self.room:doBroadcastNotify("ShowToast", "你的金币不够，遗忘卡牌需要"..self.forgetgold.."金币。") return false end
  self.wdtxobj:removeCardsToVoid(num,true)
  self.room:removePlayerMark(self.player,"@gold_num",self.forgetgold)
  local cost = self.forgetgold
  self.forgetgold = self.forgetgold + peradd
  self.room:doBroadcastNotify("ShowToast", Fk:translate(self.player.general).."币-"..cost.."遗忘卡牌。下一次遗忘卡牌需要"..self.forgetgold.."金币")
end
function Shop:upLvCards(num,peradd)   --升级卡牌
  local playergold = self.player:getMark("@gold_num") 
  -- if playergold < self.upgold then self.room:doBroadcastNotify("ShowToast", "你的金币不够，升级卡牌需要"..self.upgold.."金币。") return false end
  self.wdtxobj:upCardByPile(1)
  self.room:removePlayerMark(self.player,"@gold_num",self.upgold)
  local cost = self.upgold
  self.upgold = self.upgold + peradd
  self.room:doBroadcastNotify("ShowToast", Fk:translate(self.player.general).."币-"..cost.."升级卡牌。下一次升级卡牌需要"..self.upgold.."金币")
end

function Shop:enterShop()   --商店售卖卡牌技能（卡牌，技能....）
  local room = self.room
  -- room:setPlayerMark(self.player,"@gold_num",100)
  self.shop_chc = {"buyskills","buycards","Exist"}
  
  while true do
    local playergold = self.player:getMark("@gold_num")
    local uplvcardscost = "uplvcards:::"..self.upgold
    local forgetcardscost = "forgetcards:::"..self.forgetgold
    local chc = {"buyskills","buycards",uplvcardscost,forgetcardscost,"Exist"}

    if playergold >= self.upgold then
      table.insert(self.shop_chc,#self.shop_chc,uplvcardscost)
    end
    if playergold >= self.forgetgold then
      table.insert(self.shop_chc,#self.shop_chc,forgetcardscost)
    end
    local reply = room:askForCustomDialog(self.player,"entershop","packages/wdtx/qml/CommonChoiceBox.qml",{"entershop",self.shop_chc,chc})
    -- p(self.shop_chc)
    -- dbg()
    table.removeOne(self.shop_chc,uplvcardscost)
    table.removeOne(self.shop_chc,forgetcardscost)

    if reply and reply ~= "" then
      reply = json.decode(reply)
      if reply == "buyskills" then
        self:buySkills()
      elseif reply == "buycards" then
        self:buyCards()
      elseif string.startsWith(reply,"uplvcards") then
        self:upLvCards(1,8)
      elseif string.startsWith(reply,"forgetcards") then
        self:forgetCards(1,6)
      else
        -- p(self.curcards)
        -- dbg()
        for _, da in ipairs(self.curcards) do
          local card = Fk:getCardById(da.cid)
          if next(card.mark) then
            for m,v in pairs(card.mark) do
              if v ~= 0 then
                room:setCardMark(card,m,0)
              end
            end
          end
        end
        self.curcards = {} 
        self.curskills = {}
        self.forgetgold = 6
        self.upgold = 8
        break
      end
    end
  end
end

return Shop
